package com.ztc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @类名：FileController.java
 * @作者：李晓平
 * @时间：2018年7月17日 下午4:22:26
 * @描述：文件管理控制器
 */
@CrossOrigin
@RestController
public class FileController {

	Logger logger = LoggerFactory.getLogger(FileController.class);

	/**
	 * 根据地址下载文件
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/downloadFileByAddr")
	public void downLoadFileByAddr(HttpServletResponse response, String address, String fileName) {
		try {
			File file = new File(address);
			if (!file.exists()) {
				return;
			}
			String name = "";
			if (StringUtils.isBlank(fileName)) {
				name = java.net.URLEncoder.encode(file.getName(), "UTF-8");
			} else {
				name = java.net.URLEncoder.encode(fileName, "UTF-8");
			}
			response.setHeader("Content-Disposition", "attachment;fileName=" + name);
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");

			Long len = file.length();
			response.setContentLength(len.intValue());

			InputStream inputStream = new FileInputStream(address);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
			os.close();
			file.delete();
		} catch (Exception e) {
			logger.error("导出失败", e);
		}
	}
}
